import React from 'react';
import { Button, Modal } from 'antd';
import { FormPanel, FormPanelBtnAlign, FormPanelObject } from 'lfun-bg-comp';

const Groups: React.FC<{
  onOk: (cnt: string) => Promise<boolean>;
  title: string;
  inputLabel: string;
  required?: boolean;
  type?: 'link' | 'text' | 'default' | 'primary' | 'dashed';
  children: React.ReactNode;
}> = ({ onOk, title, inputLabel, required, type, children }) => {
  const [show, setShow] = React.useState(false);
  const [form, setForm] = React.useState<FormPanelObject>();
  return (
    <>
      <Modal
        title={title}
        open={show}
        footer={null}
        onCancel={() => {
          form.resetFields();
          setShow(false);
        }}
      >
        <FormPanel
          btnsAlign={FormPanelBtnAlign.right}
          template={[
            {
              title: '',
              inputs: [
                {
                  label: inputLabel,
                  name: 'cnt',
                  key: 'cnt',
                  required,
                  span: 24,
                },
              ],
            },
          ]}
          submitBtnText="确认"
          restBtnText="取消"
          onReset={(formPanelObject: FormPanelObject) => {
            formPanelObject.resetFields();
            setShow(false);
          }}
          onLoad={(formPanelObject: FormPanelObject) => {
            setForm(formPanelObject);
          }}
          onFinish={async (formPanelObject: FormPanelObject) => {
            if (await onOk(formPanelObject.getFieldValue('cnt'))) {
              formPanelObject.resetFields();
              setShow(false);
            }
          }}
        />
      </Modal>
      <Button
        type={type}
        onClick={() => {
          setShow(true);
        }}
      >
        {children}
      </Button>
    </>
  );
};
Groups.defaultProps = {
  required: true,
  type: 'default',
};
export default Groups;
